import uuid

from gradio.themes.builder_app import history

from mysql_qa.db.mysql_client import MysqlClient
from mysql_qa.cache.redis_client import RedisClient
from mysql_qa.retrieval.bm25_search import BM25Search

from rag_qa.core.vector_store import VectorStore
from rag_qa.core.rag_system import RAGSystem

from base.config import get_config
from base.logger import get_logger

from openai import OpenAI
import time

logger = get_logger()
config = get_config()

class IntegratedQASystem:
    def __init__(self):
        self.config = get_config()
        self.logger = get_logger()

        self.mysql_client = MysqlClient()
        self.redis_client = RedisClient()
        self.bm25_search = BM25Search()
        try:
            self.client = OpenAI(api_key=self.config.DASHSCOPE_API_KEY,
                                 base_url=self.config.DASHSCOPE_BASE_URL)
        except Exception as e:
            logger.error(f"Dash API 错误: {e}")
            raise e

        self.vector_store = VectorStore()
        self.rag_system = RAGSystem(self.vector_store, self.call_dashscope)
        self.init_conversation_table()

    def init_conversation_table(self):
        try:
            self.mysql_client.cursor.execute("""
                CREATE TABLE IF NOT EXISTS conversations(
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    session_id VARCHAR(36)NOT NULL,
                    question TEXT NOT NULL,
                    answer TEXT NOT NULL,
                    timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
                    INDEX idx_session_id(session_id)
                )
            """)
            self.mysql_client.conn.commit()
            logger.info("conversation会话表初始化完成")
        except Exception as e:
            logger.error(f"conversation会话表创建错误: {e}")
            raise e

    def call_dashscope(self,prompt):
        try:
            response = self.client.chat.completions.create(
                model=config.LLM_MODEL,
                messages=[
                    {"role": "system", "content": "你是一个助手，请回答问题。"},
                    {"role": "user", "content": prompt},
                ])
            answer = response.choices[0].message.content.strip() if response.choices else "错误，无效的LLM响应"
            return answer
        except Exception as e:
            logger.error(f"Dash API 调用失败: {e}")
            raise e

    def _fetch_recent_history(self,session_id):
        try:
            self.mysql_client.cursor.execute("""
                SELECT question,answer
                FROM conversations
                WHERE session_id = %s
                ORDER BY timestamp DESC
                LIMIT %s
            """,(session_id, 5))
            history = [{"question":row[0], "answer":row[1]}for row in self.mysql_client.cursor.fetchall()]
            history.reverse()
            logger.info(f"会话历史查询成功,会话ID:{session_id},结果：{history}")
            return history
        except Exception as e:
            logger.error(f"会话历史查询失败: {e}")
            raise e

    def get_session_history(self,session_id):
        history = self._fetch_recent_history(session_id)
        return history

    def update_session_history(self,session_id,question,answer):
        try:
            self.mysql_client.cursor.execute("""
                INSERT INTO conversations(session_id,question,answer)
                VALUES(%s,%s,%s)
            """,(session_id,question,answer))
            history = self._fetch_recent_history(session_id)
            self.mysql_client.cursor.execute("""
                DELETE FROM conversations
                WHERE session_id = %s AND id NOT IN (
                    SELECT id FROM (
                        SELECT id
                        FROM conversations
                        WHERE session_id = %s
                        ORDER BY timestamp DESC
                        LIMIT %s
                    ) AS sub
                )
            """, (session_id, session_id, 5))
            self.mysql_client.conn.commit()
            return history

        except Exception as e:
            logger.error(f"会话历史更新失败: {e}")
            raise e

    def clear_session_history(self,session_id):
        try:
            self.mysql_client.cursor.execute("""
                DELETE FROM conversations
                WHERE session_id = %s
            """,(session_id,))
            self.mysql_client.conn.commit()
            logger.info(f"会话历史清除成功,会话ID:{session_id}")
            return True
        except Exception as e:
            logger.error(f"会话历史清除失败: {e}")
            self.mysql_client.conn.rollback()
            raise False


    def query(self,query,source_filter=None,session_id=None):
        start_time = time.time()
        logger.info(f"查询处理开始时间: {start_time}，查询内容{query},来源过滤{source_filter}")
        history = self.get_session_history(session_id) if session_id else []
        answer,need_rag = self.bm25_search.search(query, threshold=0.85)
        if answer:
            logger.info(f"查询到答案:{answer}")
            if session_id:
                self.update_session_history(session_id,query,answer)

                processing_time = time.time() - start_time
                logger.info(f"查询处理结束时间: {time.time()}，处理时间: {processing_time:4f}秒")
                return answer
        elif need_rag:
            logger.info(f"未查询到相关答案，开始使用RAG系统处理问题:{query}")
            answer = self.rag_system.generate_answer(query, source_filter)
            if session_id:
                self.update_session_history(session_id,query,answer)
            processing_time = time.time() - start_time
            logger.info(f"查询处理结束时间: {time.time()}，处理时间: {processing_time:4f}秒")
            return  answer
        else:
            self.logger.info("未找到答案")
            processing_time = time.time() - start_time
            self.logger.info(f"查询处理耗时 {processing_time:.2f}秒")
            return "未找到答案"

def main():
    qa_system = IntegratedQASystem()
    session_id = uuid.uuid4()
    logger.info(f"会话ID:{session_id}")
    try:
        print("\n欢迎使用集成问答系统！")
        print(f"支持的来源: {config.VALID_SOURCES}")
        print("输入查询进行问答，输入 'exit' 退出。")
        while True:
            query = input("\n输入查询: ").strip()
            if query.lower() == "exit":
                logger.info("退出系统")
                print("再见！")
                break
            source_filter = input(f"输入来源过滤 ({'/'.join(config.VALID_SOURCES)}) (按 Enter 跳过): ").strip()
            if source_filter and source_filter not in config.VALID_SOURCES:
                logger.warning(f"无效来源 '{source_filter}'，忽略过滤")
                print(f"无效来源 '{source_filter}'，继续无过滤。")
                source_filter = None
            answer = qa_system.query(query, source_filter,session_id)
            print(f"\n最终答案: {answer}")
            history = qa_system.get_session_history(session_id)
            print("\n最近对话历史")
            for idx,entry in enumerate(history,1):
                print(f"{idx}. 问：{entry['question']} 答：{entry['answer']}")
    except Exception as e:
        logger.error(f"系统错误: {e}")
        print(f"发生错误: {e}")
    finally:
        qa_system.mysql_client.close()


if __name__ == "__main__":
    main()




